using System;
using Jalal.Library.DataStructure;
using Jalal.Library.Data;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Data.SqlTypes;
using Jalal.Library.Utility;
using BCGC.DAL;
using System.Configuration;
namespace BCGC.BLL.BusinessObject.Resource
{

    public class Patch : ResourceBase
    {
        private int patchId;
        public int PatchId
        {
            get { return patchId; }
        }

        private String fileUrl;
        public String FileUrl
        {
            get
            {
                return fileUrl;
            }
            set
            {
                fileUrl = value;
            }
        }


        public Patch()
        {
            this.patchId = 0;
            this.fileUrl = string.Empty;
            this.createDateTime = SqlDateTime.MinValue.Value;
            this.description = string.Empty;
            this.relatedGame = null;
            this.title = string.Empty;
            this.isActive = false;
            this.totalView = 0;
            this.rating = 0;
            this.totalRatingVote = 0;
        }

        public Patch(DataRow dataRow, bool fullLoad)
        {
            if (dataRow != null)
            {
                if (dataRow.Table.Columns.Contains("PatchId"))
                    this.patchId = (int)CommonUtility.FilterNull(dataRow["PatchId"], typeof(int));
                if (dataRow.Table.Columns.Contains("FileUrl"))
                    this.fileUrl = (string)CommonUtility.FilterNull(dataRow["FileUrl"], typeof(string));
                if (dataRow.Table.Columns.Contains("CreateDateTime"))
                    this.createDateTime = (DateTime)CommonUtility.FilterNull(dataRow["CreateDateTime"], typeof(DateTime));
                if (dataRow.Table.Columns.Contains("Description"))
                    this.description = (string)CommonUtility.FilterNull(dataRow["Description"], typeof(string));
                if (dataRow.Table.Columns.Contains("Title"))
                    this.title = (string)CommonUtility.FilterNull(dataRow["Title"], typeof(string));
                if (dataRow.Table.Columns.Contains("IsActive"))
                    this.isActive = (bool)CommonUtility.FilterNull(dataRow["IsActive"], typeof(bool));
                if (dataRow.Table.Columns.Contains("TotalView"))
                    this.totalView = (int)CommonUtility.FilterNull(dataRow["TotalView"], typeof(int));
                if (dataRow.Table.Columns.Contains("Rating"))
                    this.rating = (int)CommonUtility.FilterNull(dataRow["Rating"], typeof(int));
                if (dataRow.Table.Columns.Contains("TotalRatingVote"))
                    this.totalRatingVote = (int)CommonUtility.FilterNull(dataRow["TotalRatingVote"], typeof(int));

                if (fullLoad)
                    this.relatedGame = new Game(dataRow);
                else
                    this.relatedGame = null;
            }
            else
            {
                this.patchId = 0;
                this.fileUrl = string.Empty;
                this.createDateTime = SqlDateTime.MinValue.Value;
                this.description = string.Empty;
                this.relatedGame = null;
                this.title = string.Empty;
                this.isActive = false;
                this.totalView = 0;
                this.rating = 0;
                this.totalRatingVote = 0;
            }
        }

        private static ReadWriteCustomCollection<Patch> LoadFromDataTable(DataTable data)
        {
            ReadWriteCustomCollection<Patch> result = new ReadWriteCustomCollection<Patch>();

            if (data != null && data.Rows.Count > 0)
            {
                foreach (DataRow row in data.Rows)
                {
                    result.Add(new Patch(row, true));
                }
            }
            return result;
        }

        public static string UploadPatchFile(HttpPostedFile postedFile)
        {
            return FileAccessUtility.UploadFile(postedFile, ConfigurationSettings.AppSettings["FCKeditor:UserFilesPath"] 
                + "file/patch/", FileAccessUtility.FileTypes.Zip);
        }

        public static bool Create(string title, int gameId, string description, 
            string fileUrl, bool isActive)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);
            int id = ResourceData.CreateNewPatch(title, gameId, description, fileUrl, isActive);
            DataFactory.GetDataMiner().CommitTransaction();

            return (id > 0);
        }

        public static void Delete(List<int> patchesToDelete)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);
            DataTable patchFiles = ResourceData.GetPatchFileLocationsToForDelete(patchesToDelete);
            DataFactory.GetDataMiner().CommitTransaction();

            DataFactory.GetDataMiner().BeginTransaction(false);

            try
            {
                int deletedItemCount = ResourceData.DeletePatches(patchesToDelete);
                if (deletedItemCount == patchesToDelete.Count)
                    DataFactory.GetDataMiner().CommitTransaction();
                else
                    throw new Exception("Failed to delete all items");

                if (patchFiles != null && patchFiles.Rows.Count > 0)
                {
                    foreach (DataRow row in patchFiles.Rows)
                    {
                        string fileUrl = (string)row["FileUrl"];
                        if (!string.IsNullOrEmpty(fileUrl))
                            FileAccessUtility.DeleteFile(fileUrl);
                    }
                }
            }
            catch (Exception ex)
            {
                DataFactory.GetDataMiner().RollBackTransaction();
                throw ex;
            }
        }

        public static void UpdateActive(List<int> activePatches, List<int> inactivePatches)
        {
            DataFactory.GetDataMiner().BeginTransaction(false);

            try
            {
                int updatedItemCount = ResourceData.UpdateActivePatch(activePatches,
                    inactivePatches);
                if (updatedItemCount == activePatches.Count + inactivePatches.Count)
                    DataFactory.GetDataMiner().CommitTransaction();
                else
                    throw new Exception("Failed to update all items");
            }
            catch (Exception ex)
            {
                DataFactory.GetDataMiner().RollBackTransaction();
                throw ex;
            }
        }

        public static ReadWriteCustomCollection<Patch> GetAllPatches(int currentPageIndex,
            string sortOrder, int pageSize, string title, string gameTitle, DateTime? createDateFrom,
            DateTime? createDateTo, bool? isActive, out int totalData)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);

            totalData = 0;

            DataTable patchData = ResourceData.GetAllPatches(currentPageIndex, sortOrder, pageSize, 
                title, gameTitle, createDateFrom, createDateTo, isActive, out totalData);
            ReadWriteCustomCollection<Patch> patches = LoadFromDataTable(patchData);

            DataFactory.GetDataMiner().CommitTransaction();

            return patches;
        }

        public static Patch GetPatchById(int id)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);
            Patch patch = null;
            DataTable data = ResourceData.GetPatchById(id);
            if (data != null && data.Rows.Count > 0)
                patch = new Patch(data.Rows[0], true);

            DataFactory.GetDataMiner().CommitTransaction();

            return patch;
        }

        public static bool Update(int id, string title, int gameId, string description, 
            string fileUrl, bool isActive)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);
            List<int> patchesToDelete = new List<int>();
            patchesToDelete.Add(id);
            DataTable patchFiles = ResourceData.GetPatchFileLocationsToForDelete(patchesToDelete);
            DataFactory.GetDataMiner().CommitTransaction();

            if (patchFiles != null && patchFiles.Rows.Count > 0)
            {
                foreach (DataRow row in patchFiles.Rows)
                {
                    string oldFileUrl = (string)row["FileUrl"];
                    if (!string.IsNullOrEmpty(oldFileUrl))
                        FileAccessUtility.DeleteFile(oldFileUrl);
                }
            }

            DataFactory.GetDataMiner().BeginTransaction(true);
            int updateCount = ResourceData.UpdatePatch(id, title, gameId, description, fileUrl,
                isActive);
            DataFactory.GetDataMiner().CommitTransaction();

            return (updateCount > 0);
        }
    }
}
